import { createSlice, PayloadAction } from '@reduxjs/toolkit'

interface IState {
	count: number
}

const initialState: IState = {
	count: 0
}

export const counterSlice = createSlice({
	name: 'counter', // 命名空间，在调用action的时候会默认的设置为action的前缀
	// 初始值
	initialState,
	// 这里的属性会自动的导出为actions，在组件中可以直接通过dispatch进行触发
	reducers: {
		increment(preState, action: PayloadAction<number>) {
			console.log(preState, action)
			const { payload } = action
			preState.count += payload
		},
		decrement(preState, action: PayloadAction<number>) {
			const { payload } = action
			preState.count -= payload
		}
	}
})

// 导出actions
// 解构赋值并重命名
export const {
	increment: incrementActions,
	decrement: decrementActions
} = counterSlice.actions

 // 内置了thunk插件，可以直接处理异步请求
export const asyncIncrementActions = (payload: number, time = 500) => (dispatch: (arg0: { payload: number; type: string; }) => void) => {
	setTimeout(() => {
		dispatch(incrementActions(payload))
	}, time)
}

export default counterSlice.reducer